package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author: hea7en
 * @Date: 2024/5/25 3:00 PM
 * @Description: 订单相关定时任务
 */
@Slf4j
@Component
public class OrderTask {

    @Autowired
    OrderMapper orderMapper;

    /**
     * 定时任务查询超时订单，每分钟执行一次
     * 查询超过15分钟仍未支付的订单
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void timeoutOrder() {
        log.info("定时任务处理超时订单，当前时间：{}",LocalDateTime.now());

        // 15分钟之前
        LocalDateTime orderTime = LocalDateTime.now().minusMinutes(15);
        List<Orders> orderList = orderMapper.getByStatusAndTime(Orders.PENDING_PAYMENT, orderTime);
        if(orderList != null && orderList.size()>0){
            orderList.forEach(order -> {
                // 更改订单状态
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时，自动取消");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            });
        }
    }

    /**
     * 定时任务查询派送中的订单
     * 每天凌晨1点执行一次
     * 处理上一天仍在派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void deliveryOrder(){
        log.info("定时任务处理派送中的订单，当前时间：{}",LocalDateTime.now());

        LocalDateTime orderTime = LocalDateTime.now().minusHours(1);
        List<Orders> orderList = orderMapper.getByStatusAndTime(Orders.DELIVERY_IN_PROGRESS, orderTime);
        if(orderList != null && orderList.size()>0) {
            orderList.forEach(order -> {
                // 更改订单状态
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            });
        }
    }
}
